# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response
from django.template import RequestContext, Context, loader
from ingenium.forms import *
from publicidade.models import Publicidade
from django import forms
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.core.mail import send_mail
from django.views.decorators.csrf import csrf_protect
from django.core.mail import EmailMessage
from django.shortcuts import get_object_or_404, render_to_response
from django.contrib.auth import authenticate, logout, login as authlogin
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required

def news(request):
    from models import *
    from emencia.django.newsletter.models import Contact
    from forms import *

    vaga = vaga.objects.all().order_by('pub_date')
    areavaga = areavaga.objects.all()

    if request.method == 'POST':
        form = emailForm(request.POST)
        if form.is_valid():
            novo = form.save()
    else:
        form = emailForm()

    return render_to_response('ingenium/index.html', locals(), context_instance=RequestContext(request))


def homepage(request):
    from models import *
    from publicacoes.models import *
    from django.conf import settings
    from forms import *
    
    vaga = vaga.objects.all().order_by('-pub_date')
    context = {'MEDIA_URL': settings.MEDIA_URL}
    noticias = Noticias.objects.all().order_by('-publicar', '-publicacao')[:3]
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicar', '-publicacao')[:3]
    parceiros = Parceiros.objects.all()
    artigo = Artigo.objects.all().order_by('-publicar', '-publicacao')[:4]
    areavaga = areavaga.objects.all().order_by('-qtdvagas')
    enquete = Enquete.objects.all().select_related().order_by('-data_publicacao')
    publicidade = Publicidade.objects.filter(data_entrada__lte=datetime.now()).order_by('-data_entrada')[:1]

    if request.method == 'POST':
      if(request.POST['alternativa']):
        voto = Alternativa.objects.get(pk=request.POST['alternativa'])
        voto.votos += 1
        voto.save()

    return render_to_response('ingenium/index.html', locals(), context_instance=RequestContext(request))
    
def eventos(request):
    from django.conf import settings
    from publicacoes.models import *
    from models import *
    from datetime import datetime
    from publicacoes.models import *
    context = {'MEDIA_URL': settings.MEDIA_URL}
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('diadoevento')
    areavaga = areavaga.objects.all()
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    vaga = vaga.objects.all().order_by('-pub_date')[:3]
    paginator = Paginator(eventos, 20)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        eventos = paginator.page(page)
    except (EmptyPage, InvalidPage):
        eventos = paginator.page(paginator.num_pages)
		
    return render_to_response('ingenium/eventos.html', locals(), context_instance=RequestContext(request))

def artigos(request):
    from django.conf import settings
    from publicacoes.models import *
    from ingenium.models import *

    context = {'MEDIA_URL': settings.MEDIA_URL}
	
    artigo = Artigo.objects.all().order_by('-publicar','-publicacao')
    areavaga = areavaga.objects.all()
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    vaga = vaga.objects.all().order_by('-pub_date')[:3]
    paginator = Paginator(artigo, 20)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        artigo = paginator.page(page)
    except (EmptyPage, InvalidPage):
        artigo = paginator.page(paginator.num_page)

		
    return render_to_response('ingenium/artigos.html', locals(), context_instance=RequestContext(request))
@csrf_protect
def artigo(request, artigo_id):
    from publicacoes.models import *
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    artigo = Artigo.objects.get(id=artigo_id)

    return render_to_response('ingenium/artigo.html', locals(), context_instance=RequestContext(request))

def ultimasvagas(request):
    from models import vaga, vagaempresa, areavaga
    areavaga = areavaga.objects.all()
    v = vagaempresa.objects.all()
    return render_to_response('ingenium/ultimasvagas.html', locals(), context_instance=RequestContext(request))

def vaga(request, vaga_id):
    from publicacoes.models import *
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    vagaempresa = vagaempresa.objects.get(id=vaga_id)

    return render_to_response('ingenium/vaga.html', locals(), context_instance=RequestContext(request))


def cadastrarcurriculo1(request):

    from ingenium.models import *

    areavaga = areavaga.objects.all()
                                                 	
    if request.method == 'POST':
        form = usuarioForm(request.POST, request.FILES)
        if form.is_valid():
            novo_usuario = form.save()
            email = request.POST['email']
            html_content = "<a href='www.institutogalaxy.com.br'><img alt='cadastro.jpg' src='http://oi39.tinypic.com/35d5now.jpg'/></a>"
            msg = EmailMessage('Cadastro efetuado com sucesso!',html_content,'institutogalaxy@gmail.com', [email, ] )
            msg.content_subtype = "html"
            msg.send()
            return render_to_response('ingenium/cadastro-concluido.html',locals(), context_instance=RequestContext(request))
            
    else:
        form = usuarioForm()

    return render_to_response('ingenium/cadastrarcurriculo1.html', locals(), context_instance=RequestContext(request))


def cadastrarempresa(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    vaga = vaga.objects.all()
    if request.method == 'POST':
        form = empresaForm(request.POST, request.FILES)
        username = request.POST['username']
        valida = 0
        erro = ''
        use = empresa.objects.filter(username__exact = username)
        if(use):
            valida = 1
            erro = 'Já existe uma empresa com esse username!'
        if form.is_valid() and valida == 0:
            nova_empresa = form.save()
            email = request.POST['email']
            html_content = "<a href='www.institutogalaxy.com.br'><img alt='cadastro.jpg' src='http://oi41.tinypic.com/fbkdb4.jpg'/></a>"
            msg = EmailMessage('Cadastro efetuado com sucesso!',html_content,'institutogalaxy@gmail.com', [email, ] )
            msg.content_subtype = "html"
            msg.send()
            return render_to_response('ingenium/cadastro-concluido.html',locals(), context_instance=RequestContext(request,{'erro':erro,}))
    else:
        form = empresaForm()
        error = 'Verifique se seu CNPJ ou Login est�corretos!'
    return render_to_response('ingenium/cadastrar-empresa.html', locals(), context_instance=RequestContext(request))



def duvidas(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/duvidas.html', locals(), context_instance=RequestContext(request))

def empresaservico(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/empresaservico.html', locals(), context_instance=RequestContext(request))
	
def servicos(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/servicos.html', locals(), context_instance=RequestContext(request))
	
def vantagens(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/vantagens.html', locals(), context_instance=RequestContext(request))
	
def treinamento(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/treinamento.html', locals(), context_instance=RequestContext(request))
	
def aviso(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/aviso.html', locals(), context_instance=RequestContext(request))

def imprensa(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/imprensa.html', locals(), context_instance=RequestContext(request))

def carta(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/carta-apresentacao.html', locals(), context_instance=RequestContext(request))

def analise(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/analise-curriculo.html', locals(), context_instance=RequestContext(request))


def politica(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/politica.html', locals(), context_instance=RequestContext(request))

def sobre(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/sobre.html', locals(), context_instance=RequestContext(request))

def publicidade(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    return render_to_response('ingenium/publicidade.html', locals(), context_instance=RequestContext(request))

@login_required
def usuarioCadastro(request, user_id):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    user = usuario.objects.get(id=user_id, user=request.user,)
    return render_to_response('ingenium/curriculo.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioCurriculo(request,user_id):
    from ingenium.models import usuario, areavaga
    u = usuario.objects.get(pk=user_id, user=request.user,)
    areavaga = areavaga.objects.all()
    if request.method == 'POST':
        form = ateraruForm(request.POST,request.FILES, instance=u)

        if form.is_valid():
            u = form.save()

            if u:
                return HttpResponseRedirect(reverse('ingenium.views.usuarioDashboard', args=[u.id]))
    else:
        form = ateraruForm(instance=u)

    return render_to_response('ingenium/painel-usuario-curriculo.html',locals() ,context_instance=RequestContext(request))

@login_required
def usuarioCursos(request, user_id):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='1').order_by('-diadoevento')
    u = usuario.objects.get(pk=user_id, user=request.user,)

    return render_to_response('ingenium/painel-usuario-cursos.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioDashboard(request, user_id):
    from ingenium.models import usuario, areavaga, procura, vaga
    from mensagens.models import mensagemUsuario
    areavaga = areavaga.objects.all()
    vg = vaga.objects.all()
    ar = procura.objects.filter(nome__id__exact = user_id)
    u = usuario.objects.get(pk=user_id, user=request.user,)
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='1').order_by('-diadoevento')[:5]
    mU = mensagemUsuario.objects.filter(data__lte=datetime.now())

    return render_to_response('ingenium/painel-usuario-dashboard.html', locals(),context_instance=RequestContext(request))

@login_required
def usuariosugestao(request, user_id):
    from ingenium.models import usuario, areavaga
    from mensagens.models import mensagemUsuario
    areavaga = areavaga.objects.all()
    u = usuario.objects.get(pk=user_id, user=request.user,)

    if request.method == 'POST':
        form = FormContato(request.POST)

        if form.is_valid():
            form.enviar()
            mostrar = 'Menssagem enviada!'
            form = FormContato()
    else:
        form = FormContato()
    return render_to_response('ingenium/painel-usuario-sugestao.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioInterna(request, user_id):
    from ingenium.models import usuario,areavaga
    from mensagens.models import mensagemUsuario
    areavaga = areavaga.objects.all()
    u = usuario.objects.get(pk=user_id, user=request.user,)
    mU = mensagemUsuario.objects.filter(data__lte=datetime.now())
    return render_to_response('ingenium/painel-usuario-interna.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioMensagens(request, cod):
    from ingenium.models import usuario,areavaga
    from mensagens.models import mensagemUsuario
    areavaga = areavaga.objects.all()
    u = usuario.objects.get(pk=cod, user=request.user,)
    mU = mensagemUsuario.objects.filter(data__lte=datetime.now())

    return render_to_response('ingenium/painel-usuario-mensagens.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioPerguntas(request, user_id):
    from ingenium.models import usuario,areavaga
    u = usuario.objects.get(pk=user_id, user=request.user,)
    areavaga = areavaga.objects.all()

    return render_to_response('ingenium/painel-usuario-perguntas.html', locals(),context_instance=RequestContext(request))

@login_required
def usuarioRelatorio(request, user_id):
    from ingenium.models import usuario
    u = usuario.objects.get(pk=user_id, user=request.user,)

    return render_to_response('ingenium/painel-usuario-relatorio.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaVagas(request,cad):
    from ingenium.models import empresa,areavaga
    areavaga = areavaga.objects.all()
    e = empresa.objects.get(pk=cad, user=request.user,)

    if request.method == 'POST':
        form = vagaForm(request.POST)
        if form.is_valid():
            nova_vaga = form.save()
            return render_to_response('ingenium/painel-empresa-dashboard.html',locals(), context_instance=RequestContext(request,{'cad':cad}))
    else:
        form = vagaForm()

    return render_to_response('ingenium/painel-empresa-cadastrar-vagas.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaInterna(request, user_id):
    from ingenium.models import empresa, areavaga
    from mensagens.models import mensagemEmpresa
    areavaga = areavaga.objects.all()   
    e = empresa.objects.get(pk=user_id, user=request.user,)
    mE = mensagemEmpresa.objects.filter(data__lte=datetime.now())
    return render_to_response('ingenium/painel-empresa-interna.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaCadastro(request,user_id):
    from ingenium.models import empresa, areavaga
    e = empresa.objects.get(pk=user_id, user=request.user,)
    areavaga = areavaga.objects.all()
    if request.method == 'POST':
        form = altempForm(request.POST,request.FILES, instance=e)

        if form.is_valid():
            e = form.save()

            if e:
                return HttpResponseRedirect(reverse('ingenium.views.empresaDashboard', args=[e.id]))
    else:
        form = altempForm(instance=e)

    return render_to_response('ingenium/painel-empresa-cadastro.html',locals() ,context_instance=RequestContext(request))

@login_required
def empresaDashboard(request, dash_id):
    from ingenium.models import *
    areavaga = areavaga.objects.all()
    from mensagens.models import mensagemEmpresa
    req = requisicao.objects.filter(id__exact=dash_id)
    vg = vaga.objects.all()
    if(req):
        o = requisicao.objects.get(pk=dash_id)
    e = empresa.objects.get(pk=dash_id, user=request.user,)

    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='0').order_by('-diadoevento')[:5]
    mE = mensagemEmpresa.objects.filter(data__lte=datetime.now())

    return render_to_response('ingenium/painel-empresa-dashboard.html', locals(),context_instance=RequestContext(request,{'req':req}))

@login_required
def empresaGerenciar(request, vaga_id):
    from ingenium.models import empresa,requisicao,areavaga
    areavaga = areavaga.objects.all()
    e = empresa.objects.get(pk=vaga_id, user=request.user,)
    req = requisicao.objects.filter(id__exact=vaga_id)
    if(req):
        requisicao = requisicao.objects.get(pk=vaga_id)

    return render_to_response('ingenium/painel-empresa-gerenciar-vagas.html', locals(),context_instance=RequestContext(request,{'req':req}))

@login_required
def empresaRelatorio(request, rel):
    from ingenium.models import *
    areavaga = areavaga.objects.all()
    e = empresa.objects.get(pk=rel, user=request.user,)
    #empresa = empresa.objects.all()
    email = request.user
    empres = ''
    quant = 0
    selec = ''
    #email = request.session['user']
    empre = vagaempresa.objects.filter(empresa__id__exact = rel)
    quant = empre.count()
    if(quant > 0 ):
            selec = selecao.objects.filter(recrutamento__vagaempresa__empresa__id__exact = rel)


    return render_to_response('ingenium/painel-empresa-relatorios.html', locals(),context_instance=RequestContext(request,{'empre':empre,'selec':selec,'quant':quant,}))

@login_required
def empresaSugestao(request, user_id):
    from ingenium.models import *
    areavaga = areavaga.objects.all()

    e = empresa.objects.get(pk=user_id, user=request.user,)

    if request.method == 'POST':
        form = SugestaoForm(request.POST)

        if form.is_valid():
            form.enviar()
            mostrar = 'Menssagem enviada!'
            form = SugestaoForm()
    else:
        form = SugestaoForm()
    return render_to_response('ingenium/painel-empresa-sugestao.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaMensagens(request, cod):
    from ingenium.models import empresa,areavaga
    from mensagens.models import mensagemEmpresa
    e = empresa.objects.get(pk=cod, user=request.user,)
    areavaga = areavaga.objects.all()
    mE = mensagemEmpresa.objects.filter(data__lte=datetime.now())

    return render_to_response('ingenium/painel-empresa-mensagens.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaCursos(request, curso_id):
    from ingenium.models import empresa, areavaga
    e = empresa.objects.get(pk=curso_id, user=request.user,)
    areavaga = areavaga.objects.all()
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='0').order_by('-diadoevento')

    return render_to_response('ingenium/painel-empresa-cursos.html', locals(),context_instance=RequestContext(request))

@login_required
def empresaPerguntas(request,per):
    from ingenium.models import *
    areavaga = areavaga.objects.all()
    e = empresa.objects.get(pk=per, user=request.user,)

    return render_to_response('ingenium/painel-empresa-perguntas.html', locals(),context_instance=RequestContext(request))


def destaques(request):
    from publicacoes.models import *
    from models import *

    areavaga = areavaga.objects.all()

    vaga = vaga.objects.all().order_by('-pub_date')
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicar','-publicacao')
    noticias = Noticias.objects.all().order_by('-publicar','-publicacao')[:3]
    paginator = Paginator(destaques, 15)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        destaques = paginator.page(page)
    except (EmptyPage, InvalidPage):
        destaques = paginator.page(paginator.num_page)

	
    return render_to_response('ingenium/destaques.html', locals(), context_instance=RequestContext(request))	

@csrf_protect
def destaque(request, destaques_id):
    from publicacoes.models import *
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    destaques = Destaques.objects.get(id=destaques_id)
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    noticias = Noticias.objects.all().order_by('-publicar','-publicacao')[:3]

    return render_to_response('ingenium/destaque.html', locals(), context_instance=RequestContext(request))

def noticias(request):
    from publicacoes.models import *
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicar','-publicacao')[:3]
    noticias = Noticias.objects.all().order_by('-publicacao')
    paginator = Paginator(noticias, 10)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        noticias = paginator.page(page)
    except (EmptyPage, InvalidPage):
        noticias = paginator.page(paginator.num_page)

	
    return render_to_response('ingenium/noticias.html', locals(), context_instance=RequestContext(request),)

@csrf_protect
def noticia(request, noticias_id):
    from models import *
    from publicacoes.models import *

    areavaga = areavaga.objects.all()
    vaga = vaga.objects.all().order_by('-pub_date')
    destaques = Destaques.objects.all().order_by('-publicar','-publicacao')[:3]
    noticias = Noticias.objects.get(id=noticias_id)

    return render_to_response('ingenium/noticia.html', locals(), context_instance=RequestContext(request))
	
    return render_to_response('ingenium/noticia.html', locals(), context_instance=RequestContext(request))



def login(request):
    from models import *
    from publicacoes.models import *
    from mensagens.models import mensagemUsuario, mensagemEmpresa
    from django.conf import settings
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    areavaga = areavaga.objects.all()
    vagas = vaga.objects.all().order_by('-pub_date')
    empresas = empresa.objects.all()
    usuarios = usuario.objects.all()
    url = ''
    use = None
    emp = None
    mU = None
    mE = None
    eventos = None
    if(request.POST.get('username')):
        user = request.POST.get('username')
        emp = empresa.objects.filter(username__icontains = user)
        if(emp):
            emp = empresa.objects.get(username = user)
            url = '/painel-empresa-dashboard.html'
            mE = mensagemEmpresa.objects.filter(data__lte=datetime.now())
            eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='0').order_by('-diadoevento')
        else:
            emp = usuario.objects.filter(email__icontains = user)
            if(emp):
                emp = usuario.objects.get(email = user)
                url = '/painel-usuario-dashboard.html'
                mU = mensagemUsuario.objects.filter(data__lte=datetime.now())
                ar = procura.objects.filter(nome = emp)
                eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='1').order_by('-diadoevento')
                vg = vaga.objects.all()
    if request.user.id:
        use = request.user.username
        uses = request.user.email
        emp = empresa.objects.filter(username__icontains = use)
        if(emp):
            emp = empresa.objects.get(username = use)
            url = '/painel-empresa-dashboard.html'
            mE = mensagemEmpresa.objects.filter(data__lte=datetime.now())
            eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='0').order_by('-diadoevento')
        else:
            emp = usuario.objects.filter(email__icontains = uses)
            if(emp):
                emp = usuario.objects.get(email = uses)
                mU = mensagemUsuario.objects.filter(data__lte=datetime.now())
                url = '/painel-usuario-dashboard.html'
                ar = procura.objects.filter(nome = emp)
                vg = vaga.objects.all()
                eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).filter(destinado__exact='1').order_by('-diadoevento')
        return render_to_response('ingenium'+url,context_instance=RequestContext(request, {'u':emp,'e':emp,'areavaga':areavaga,'mU':mU,'mE':mE,'eventos':eventos,'vg':vg,'ar':ar}))

    if request.POST:
        emailUser = request.POST.get('username')
        senhaUser = request.POST.get('password')
        u = authenticate(username=emailUser, password=senhaUser)
        if u is not None:
           if u.is_active:
               authlogin(request, u)
#               if request.POST.get('next'):
#                   return HttpResponseRedirect(request.POST.get('next'))

               return render_to_response('ingenium'+url, context_instance=RequestContext(request,{'u':emp,'e':emp,'areavaga':areavaga,'mU':mU,'mE':mE,'eventos':eventos,'vg':vg,'ar':ar}))

    return render_to_response('ingenium/index.html',locals(), context_instance=RequestContext(request, {'erro':'Dados Invalidos!'}))

def procura(request):
    from models import *
    import datetime
    areavaga = areavaga.objects.all()
    vagas = vaga.objects.values_list('id', flat = True)
    vg = None
    p = None
    teste = None
    teste2 = None
    us = request.user
    use = usuario.objects.filter(email__exact = us)
    use = use.get()
    use = use.id
    for i in vagas:
        qtd = 1
        if ('vaga'+str(i)) in request.POST:
            #vag = vaga.objects.get(id = qtd )
            p = procura.objects.get_or_create(nome_id = use,vaga_id = i)
            #p.save()
        qtd = qtd+1
    proc = procura.objects.filter(nome__id__exact = use)
    return render_to_response('ingenium/resultado-condidata.html',locals(),context_instance=RequestContext(request, {'areavaga':areavaga,'quant':use, 'bus':vg, 'are':request.POST, 'pro':p,'qtd':qtd,'teste':teste,'teste2':teste2,'i':i,'proc':proc}))


def sair(request):
    logout(request)
    return redirect('/index/')

def contato(request):
    from ingenium.models import *

    areavaga = areavaga.objects.all()
    if request.method == 'POST':
        form = FormContato(request.POST)

        if form.is_valid():
            form.enviar()
            mostrar = 'Menssagem enviada!'
            form = FormContato()
    else:
        form = FormContato()	
	
    return render_to_response('ingenium/contato.html',locals(),context_instance=RequestContext(request),)



def buscae(request):
    from models import *
    from publicacoes.models import *
    from django.conf import settings
    vaga = vaga.objects.all().order_by('-pub_date')
    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    areavaga = areavaga.objects.all()
    quant = 0
    if((request.GET['keyword']!='')or(request.GET['id_vaga_descricao']!='')):
        itens = vagaempresa.objects.filter(vaga__descricao__icontains = request.GET['keyword'],vaga__area__areaatuacao__icontains = request.GET['id_vaga_descricao'])
        if(itens):
            quant = itens.count()
    #    item = itens.get(pk=1)

        c = Context({
            'itens_busca': itens, 'quant':quant, 'bus':request.GET['keyword'],'are':request.GET['id_vaga_descricao'],
        })
        return render_to_response('ingenium/resultado-busca.html', locals() ,context_instance=RequestContext(request,c))


    return render_to_response('ingenium/index.html', locals(), context_instance=RequestContext(request,{'msg':'Por Favor, preencha pelo menos um campo de busca!'}))

def buscap(request):
    from models import *
    from publicacoes.models import *
    from django.conf import settings

    eventos = Eventos.objects.filter(diadoevento__gte=datetime.now()).order_by('-diadoevento')
    destaques = Destaques.objects.all().order_by('-publicacao')[:3]
    areavaga = areavaga.objects.all()
    vaga = vaga.objects.all().order_by('-pub_date')

    quante = 0
    if((request.GET['keywordp']!='')or(request.GET['id_select']!='')):
        ites = procura.objects.filter(vaga__descricao__icontains = request.GET['keywordp'],vaga__area__areaatuacao__icontains = request.GET['id_select'])
        if(ites):
            quante = ites.count()
        c = Context({
            'itens_busca': ites, 'quant':quante, 'bus':request.GET['keywordp'], 'are':request.GET['id_select'],
        })
        return render_to_response('ingenium/busca.html', locals() ,context_instance=RequestContext(request,c))


    return render_to_response('ingenium/index.html', locals() ,context_instance=RequestContext(request,{'msg':'Por Favor, preencha pelo menos um campo de busca!'}))

def page_not_found(request):
	return render_to_response('ingenium/404.html', locals(), context_instance=RequestContext(request))
